﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using Microsoft.Practices.Unity;
using WebShop.Contracts;
using WebShop.DAL.Interfaces;
using WebShop.DAL.Repositories;
using Webdiyer.WebControls.Mvc;
using WebShop.Infrastructure;
using WebShop.Models;
using WebShop.ViewModels;

namespace WebShop.Controllers
{
    [Authorize]
    [HandleErrors]
    public class OrdersController : Controller
    {
        private const int PAGE_SIZE = 20;

        [Dependency]
        public IOrderRepository Orders { get; set; }

        [Dependency]
        public IProductRepository Products { get; set; }

        [Dependency]
        public IShipperRepository Shippers { get; set; }

        [Dependency]
        public IUserRepository Users { get; set; }

        [Dependency]
        public ProductsCartRepository ProductsCart { get; set; }

        //
        // GET: /Orders/

        public ViewResult Index(int pageIndex = 1, string userName = "")
        {
            PagedList<Order> filteredOrders = null;
            if (User.IsInRole(Constants.ROLE_ADMIN))
            {
                if (userName == string.Empty)
                {
                    filteredOrders = Orders.FindList(pageIndex, PAGE_SIZE);
                }
                else
                {
                    filteredOrders = Orders.FindList(pageIndex, PAGE_SIZE, o => o.User.UserName == userName);
                }
            }
            else
            {
                filteredOrders = Orders.FindList(pageIndex, PAGE_SIZE, o => o.User.UserName == User.Identity.Name);
            }

            return View(filteredOrders);
        }

        //
        // GET: /Orders/Details/5

        public ViewResult Details(int id)
        {
            Order order = Orders.Get(id);

            ICollection<Order_Detail> orderDetails = order.Order_Details;
            ProductsCart cart = ProductsCart.LoadCart(orderDetails);
            List<Product> productsDb = Products.FindList(1, int.MaxValue, p => cart.ProductIDs.Contains(p.ProductID));
            List<ProductInCart> products = cart.FillProductsInfo(productsDb);

            return View(new ShoppingCartViewModel(order, products));
        }

        //
        // GET: /Orders/Create

        public ActionResult Create()
        {
            ViewBag.ShipVia = new SelectList(Shippers.List(), "ShipperID", "CompanyName");
            ViewBag.UserID = new SelectList(Users.List(), "UserId", "UserName");

            return View();
        }

        //
        // POST: /Orders/Create

        [HttpPost]
        [ValidateAntiForgeryToken]
        [ValidateInput(false)]
        public ActionResult Create(Order order)
        {
            if (ModelState.IsValid)
            {
                order.OrderDate = DateTime.Now;
                User user = Users.Find(u => u.UserName == User.Identity.Name);
                order.User = user;

                ProductsCart cart = ProductsCart.LoadCart(HttpContext);
                List<Product> productsDb = Products.FindList(1, int.MaxValue, p => cart.ProductIDs.Contains(p.ProductID));
                List<ProductInCart> products = cart.FillProductsInfo(productsDb);
                foreach (ProductInCart item in products)
                {
                    Order_Detail det = new Order_Detail();
                    det.Quantity = item.Quantity;
                    det.Product = item.Product;
                    det.Order = order;
                    det.Discount = 0;
                    det.UnitPrice = item.Product.UnitPrice.Value;
                    order.Order_Details.Add(det);
                }

                Orders.Create(order);
                Orders.SaveChanges();

                cart.Clear();
                ProductsCart.SaveCart(HttpContext, cart);

                return RedirectToAction("Index");
            }

            ViewBag.ShipVia = new SelectList(Shippers.List(), "ShipperID", "CompanyName", order.ShipVia);
            ViewBag.UserID = new SelectList(Users.List(), "UserId", "UserName", order.UserID);
            return View(order);
        }

        //
        // GET: /Orders/Edit/5

        public ActionResult Edit(int id)
        {
            Order order = Orders.Get(id);
            ViewBag.ShipVia = new SelectList(Shippers.List(), "ShipperID", "CompanyName", order.ShipVia);
            ViewBag.UserID = new SelectList(Users.List(), "UserId", "UserName", order.UserID);

            return View(order);
        }

        //
        // POST: /Orders/Edit/5

        [HttpPost]
        [ValidateInput(false)]
        [ValidateAntiForgeryToken]
        public ActionResult Edit(Order order)
        {
            if (ModelState.IsValid)
            {
                Orders.Edit(order);
                Orders.SaveChanges();
                return RedirectToAction("Index");
            }
            ViewBag.ShipVia = new SelectList(Shippers.List(), "ShipperID", "CompanyName", order.ShipVia);
            ViewBag.UserID = new SelectList(Users.List(), "UserId", "UserName", order.UserID);
            return View(order);
        }

        //
        // GET: /Orders/Delete/5

        public ActionResult Delete(int id)
        {
            Order order = Orders.Get(id);

            return View(order);
        }

        //
        // POST: /Orders/Delete/5

        [HttpPost, ActionName("Delete")]
        public ActionResult DeleteConfirmed(int id)
        {
            Orders.Delete(id);
            Orders.SaveChanges();

            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            //db.Dispose();
            base.Dispose(disposing);
        }
    }
}